<?php


namespace PKApp\Links;

use PKApp\Links\Classes\TraitLInks;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Date;
use PKFrame\DataHandler\Numbers;

class AdminSetLinks extends AdminController
{

    use TraitLInks;

    public function Main()
    {
        $this->callOfSellFunc();
    }

    protected function apiByCreate()
    {
        $post = $this->model();
        unset($post['id']);
        Numbers::IsId($post['categoryId']) ?: $this->noticeByJson('Links_CategoryID_Empty');
        $post['listSort'] = 0;
        if (request()->has('createTime','post')) {
            $createTime = request()->post('createTime');
            Date::isTimeStamp($createTime,'Format_timestamp');
            $post['createTime'] = $createTime;
        } else {
            $post['createTime'] = time();
        }
        $post['isIndex'] = Numbers::To(request()->post('isIndex'));
        $this->serviceOfLinks()->Add($post);
        $this->inputSuccess();
    }

    protected function apiByChange()
    {
        $post = $this->model();
        $id = request()->post('id');
        Numbers::IsId($id) ?: $this->noticeByJson('Links_IdEmpty');
        $post['isIndex'] = Numbers::To(request()->post('isIndex'));
        $this->serviceOfLinks()->UpdateById($id, $post);
        $this->inputSuccess();
    }

    protected function apiByDel()
    {
        $id = request()->post('id');
        Numbers::IsId($id) ?: $this->noticeByJson('Links_IdEmpty');
        $this->serviceOfLinks()->DeleteById($id);
        $this->inputSuccess();
    }

    protected function model(): array
    {
        $post = $this->checkModel(['id', 'categoryId', 'siteName', 'siteLogo', 'siteUrl', 'siteInfo', 'isIndex']);
        $post['siteName'] = $this->checkPostFieldIsEmpty('siteName', 'Links_SiteNameEmpty');
        $post['siteUrl'] = $this->checkPostFieldIsEmpty('siteUrl', 'Links_SiteUrlEmpty');
        $post['siteId'] = $this->loginUser()->SiteId;
        return $post;
    }

    protected function apiBySortIndex()
    {
        $id = request()->post('id');
        Numbers::IsId($id) ?: $this->noticeByJson('Links_IdEmpty');
        $this->serviceOfLinks()->UpdateById($id, ['listSort' => Numbers::To(request()->post('sortIndex'))]);
        $this->inputSuccess();
    }
}
